//
//  XGImageManager.m
//  Instagram
//
//  Created by monkey on 2019/4/14.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <AVOSCloud/AVOSCloud.h>

#import "XGImageManager.h"

/// 图片缓存
static NSCache *_cache;

@implementation XGImageManager

#pragma mark - 单例

+ (instancetype)shared
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        // 注册内容警告通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidReceiveMemoryWarningNotification) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    });
    
    return instance;
}

+ (void)initialize
{
    _cache = [[NSCache alloc] init];
    _cache.totalCostLimit = 20 * 1000 * 1000;    // 缓存容量 单位字节 10 * 1000 * 1000 = 20Mb
    _cache.countLimit = 100;        // 最大缓存个数
}

- (void)dealloc
{
    // 移除通知监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 事件监听

/// 内存警告通知
- (void)applicationDidReceiveMemoryWarningNotification
{
    [_cache removeAllObjects];
}

#pragma mark - 网络加载图片

+ (void)imageForAVFile:(AVFile *)avfile placeholderImage:(UIImage *)placeholderImage imageSize:(CGSize)imageSize backgroundColor:(UIColor *)backgroundColor isUserIcon:(BOOL)isUserIcon completion:(void (^)(UIImage * _Nullable image))completion
{
    // 如果内存缓存有图片
    if ([_cache objectForKey:avfile.objectId]) {
        completion([_cache objectForKey:avfile.objectId]);
        return;
    }
    
    // 如果本地缓存有图片
    [avfile downloadWithCompletionHandler:^(NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (error) {
            completion(placeholderImage);
            return;
        }
        
        // 本地磁盘有 或者 网络下载成功
        UIImage *image = [UIImage imageWithContentsOfFile:filePath.path];
        UIImage *newImage = nil;
        if (isUserIcon) {
            newImage = [image circleImage:imageSize backgroundColor:backgroundColor];
        } else {
            newImage = [image scaleToSize:imageSize backgroundColor:backgroundColor];
        }
        
        // 保存至缓存
        [_cache setObject:newImage forKey:avfile.objectId];
        completion(newImage);
    }];
}

+ (void)imageForAVFile:(AVFile *)avfile placeholderImage:(UIImage *_Nullable)placeholderImage imageSize:(CGSize)imageSize completion:(void(^)(UIImage *_Nullable image))completion
{
    [self imageForAVFile:avfile placeholderImage:placeholderImage imageSize:imageSize backgroundColor:[UIColor whiteColor] isUserIcon:NO completion:completion];
}

@end
